import axios from 'axios'
import { createBrowserRouter } from 'react-router-dom'
import { checkStatus } from './utils'
// import JSEncrypt from 'jsencrypt'
import JSEncryptLong from 'encryptlong'

// 公钥加密 私钥解密
let privateKey = import.meta.env.VITE_PRIVATE_KEY
let publicKey = import.meta.env.VITE_PUBLIC_KEY

let entrypt =  new JSEncryptLong()
entrypt.setPrivateKey(publicKey)

let decrypt =  new JSEncryptLong()
decrypt.setPrivateKey(privateKey)

// 创建路由对象  可以使用route.navigate() 跳转页面
let route = createBrowserRouter([{path:'/'}])


function isEntrypt(url){
  let envEntrypt = import.meta.env.VITE_ENTRYPT === 'on'

  let excludeUrl = [
    '/api/user/updateUserInfo'
  ].includes(url)

  return Boolean(!excludeUrl && envEntrypt)
}


const instance = axios.create({
  baseURL: import.meta.env.VITE_API_URL,
  timeout: 8000
})

instance.interceptors.request.use((config) => {
  let token = localStorage.getItem('token')
  let headers = {}
  if (token) {
    headers = {
      Authorization: 'Bearer ' + token,
    }
  }
  config.headers = Object.assign(
    {
      Accept: 'application/json, text/plain, */*',
      'Content-Type': 'application/json; charset=UTF-8',
    },
    config.headers,
    headers
  )
  
  if (isEntrypt(config.url)) {
    try {
      config.data = entrypt.encryptLong(JSON.stringify(config.data))
    } catch (error) {
      console.log(error);
    }
  }
  
  return config
})

instance.interceptors.response.use(
  (response) => {
    if(response.data && isEntrypt(response.config.url)) {
        console.time('接口解密时间:')
        let result = decrypt.decryptLong(response.data)
        response.data = JSON.parse(decodeURIComponent(result)) // 后端数据需要encodeURIComponent转码，前端解码 防止中文乱码
        console.timeEnd('接口解密时间:')
    }
    return Promise.resolve(checkStatus(response))
  },
  (error) => {
    if (error.response){
      let { response } = error
      if(response.data && isEntrypt(response.config.url)) {
        response.data = JSON.parse(decrypt.decryptLong(response.data))
      }
      return Promise.reject(checkStatus(error.response))
    } else if (error.code === 'ECONNABORTED' && error.message.indexOf('timeout') !== -1) {
      return Promise.reject({message:'请求超时'})
    } else {
      return Promise.reject(error)
    }
  }
)

// 统一处理错误状态码
function handleError(ifHandleError,error){
  if (!ifHandleError) return
  // alert(error.message || '请求处理失败!')
  if(error.status === 401){
    localStorage.removeItem('userInfo')
    // route.navigate(0)
  }
}


const request = async (opt) => {
  const options = Object.assign({method:'GET',ifHandleError: true},opt)

  try {
    const res = await instance(options)
    if(!res.code){
      handleError(options.ifHandleError,res)
    }
    return res
  } catch (error) {
    handleError(options.ifHandleError,error)
    return error
  }

}


export default request